{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "9a898482",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import os\n",
    "from os import listdir\n",
    "from sklearn.model_selection import KFold,StratifiedKFold\n",
    "import random\n",
    "from sklearn.model_selection import KFold\n",
    "def loadfile(filename):\n",
    "    f=open(filename,'r')\n",
    "    x_data=[]\n",
    "    y_data=[]\n",
    "    for line in f.readlines():\n",
    "        x_data_temp=[]\n",
    "        temp=line.strip().split(' ')\n",
    "        \n",
    "        for i in range(len(temp)-1):\n",
    "            x_sx=float(temp[i+1].split(\":\")[1])\n",
    "#             print(x_sx)\n",
    "            x_data_temp.append(x_sx)\n",
    "        \n",
    "        x_data.append(x_data_temp)\n",
    "        y_data.append(int(temp[0]))\n",
    "    f.close()\n",
    "    return np.array(x_data), np.array(y_data)\n",
    "def savelibsvm(x, y, filename):\n",
    "    f =open(filename, \"w\", encoding='UTF-8')\n",
    "    m, n = x.shape\n",
    "    for index in range(m):\n",
    "        out = str(y[index])\n",
    "        for i in range(n):\n",
    "            out = out + \"\\t{}:{}\".format(i+1,x[index,i])\n",
    "        out = out + \"\\n\"\n",
    "        f.writelines(out)\n",
    "    f.close()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f2dfec00",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "acq_vs_cocoa完成！\n",
      "acq_vs_coffee完成！\n",
      "coffee_vs_cocoa完成！\n",
      "grain vs cotton完成！\n",
      "trade_vs_jobs完成！\n",
      "acq_vs_cocoa完成！\n",
      "acq_vs_coffee完成！\n",
      "coffee_vs_cocoa完成！\n",
      "grain vs cotton完成！\n",
      "trade_vs_jobs完成！\n",
      "acq_vs_cocoa完成！\n",
      "acq_vs_coffee完成！\n",
      "coffee_vs_cocoa完成！\n",
      "grain vs cotton完成！\n",
      "trade_vs_jobs完成！\n",
      "acq_vs_cocoa完成！\n",
      "acq_vs_coffee完成！\n",
      "coffee_vs_cocoa完成！\n",
      "grain vs cotton完成！\n",
      "trade_vs_jobs完成！\n",
      "acq_vs_cocoa完成！\n",
      "acq_vs_coffee完成！\n",
      "coffee_vs_cocoa完成！\n",
      "grain vs cotton完成！\n",
      "trade_vs_jobs完成！\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "#表示k折的次数\n",
    "KFold_num = 5\n",
    "# 放入数据的文件夹\n",
    "data_dir_all = 'imbalance_data_txt'\n",
    "\n",
    "# 交叉验证产生的数据集存放的文件夹\n",
    "data_after = 'k_fold_reu'\n",
    "# 表示几折交叉验证\n",
    "n_k = 3\n",
    "dircontent = listdir(data_dir_all)\n",
    "for k_num in range(KFold_num):\n",
    "    # 创建放入数据的文件夹\n",
    "    try:\n",
    "        os.mkdir(data_after)\n",
    "    except OSError as error:\n",
    "        pass\n",
    "    # 每个k折的数据集存放目录\n",
    "    save_dir_ls = \"{}/{}\".format(data_after,k_num)\n",
    "    try:\n",
    "        os.mkdir(save_dir_ls)\n",
    "    except OSError as error:\n",
    "        pass\n",
    "    \n",
    "    for dir_file in dircontent:\n",
    "        dir_new = dir_file.split(\".\")[0]\n",
    "        try:\n",
    "            os.mkdir('{}/{}'.format(save_dir_ls, dir_new))\n",
    "        except OSError as error:\n",
    "            pass\n",
    "        x, y = loadfile(\"{}/{}\".format(data_dir_all, dir_file))\n",
    "        \n",
    "        skf = KFold(n_splits=n_k, shuffle=True, random_state=random.randint(1000,10000))\n",
    "        i = 0\n",
    "        for train_index, test_index in skf.split(x, y):\n",
    "            i = i + 1\n",
    "            X_train, X_test = x[train_index], x[test_index]\n",
    "\n",
    "            y_train, y_test = y[train_index], y[test_index] \n",
    "            savelibsvm(X_train, y_train, \"{}/{}/{}train.txt\".format(save_dir_ls, dir_new, i))\n",
    "            savelibsvm(X_test, y_test, \"{}/{}/{}test.txt\".format(save_dir_ls, dir_new, i))\n",
    "        print(\"{}完成！\".format(dir_new))\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4336491b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 2], [2, 3], [1, 2], [3]]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "a = [[1,2],[2,3]]\n",
    "b = [[1,2],[3]]\n",
    "a= a + b\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bcfa38f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py36",
   "language": "python",
   "name": "py36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
